class Solution
{
public:
    int minIncrements(int n, vector<int> &cost)
    {
        cost.insert(cost.begin(), 0);
        vector<int> maxLeafPathVal(n + 1, 0);

        for (int i = n; i > 0; --i)
        {
            maxLeafPathVal[i] += cost[i];
            maxLeafPathVal[i / 2] = max(maxLeafPathVal[i / 2], maxLeafPathVal[i]);
        }

        int minInc = 0;
        function<void(int)> dfs = [&](int node)
        {
            if (node * 2 > n)
            {
                return;
            }
            minInc += abs(maxLeafPathVal[node * 2] - maxLeafPathVal[node * 2 + 1]);
            dfs(node * 2);
            dfs(node * 2 + 1);
        };

        dfs(1);
        return minInc;
    }
};